Skip to content

fix(FOUR-34260): store per-user random TOTP secrets for 2FA - #9127

Open
gproly wants to merge 33 commits into
developfrom
bugfix/FOUR-34260
Open

gproly wants to merge 33 commits into
developfrom
bugfix/FOUR-34260

Conversation

@gproly

@gproly gproly commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Stop deriving 2FA secrets from public uuid and username, which allowed anyone with those fields to forge valid codes. Generate secrets with TOTP::generate(), persist encrypted on users.two_factor_secret, and add regression tests for predictable-code rejection and normal 2FA flow.

Existing Authenticator App enrollments must scan a new QR after deploy.

https://processmaker.atlassian.net/browse/FOUR-34260

ci:deploy

Stop deriving 2FA secrets from public uuid and username, which allowed
anyone with those fields to forge valid codes. Generate secrets with
TOTP::generate(), persist encrypted on users.two_factor_secret, and add
regression tests for predictable-code rejection and normal 2FA flow.

Existing Authenticator App enrollments must scan a new QR after deploy.

https://processmaker.atlassian.net/browse/FOUR-34260
@cursor

cursor Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

PR Summary

High Risk
Changes authentication secrets, login/2FA gating, and profile update authorization; existing authenticator enrollments require re-scanning a new QR after deploy.

Overview
Fixes a critical 2FA flaw where codes could be forged from public uuid and username. TOTP secrets are now generated with TOTP::generate(), stored encrypted on users.two_factor_secret and users.two_factor_delivery_secret (new migration), and hidden from API responses.

The login and 2FA web flow gains session snapshots of challenge methods and delivery email/cell, delivery step-up before authenticator QR enrollment, pending authenticator secrets in session until a 6-digit code is verified, and stricter rules for when the web 2FA gate clears. Controllers reload the user where needed; logout clears the expanded 2FA session keys.

Self-service user API updates are blocked (422) when changing preferences_2fa, email, or cell until the same principal completes web 2FA—closing Bearer-token bypasses—while admins can still update other users.

2FA Blade views are refactored to auth.layouts.auth. Regression tests cover predictable-code rejection, enrollment flows, mixed methods, and API gates.

Reviewed by Cursor Bugbot for commit f073fb0. Bugbot is set up for automated code reviews on this repo. Configure here.

@julceslauhub julceslauhub left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

approved

… users

Stop deriving 2FA codes from public uuid and username. Persist CSPRNG
secrets encrypted on users.two_factor_secret, add regression tests, and
on login route legacy users without a secret to QR (auth app only) or
force a fresh email/SMS code.

Run the migration on deploy. Authenticator App users must scan a new QR.

https://processmaker.atlassian.net/browse/FOUR-34260

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@nolanpro

Copy link
Copy Markdown
Contributor

QA server K8S was successfully deployed https://tenant-1.ci-acbfe4bfe2.engk8s.processmaker.net

- TwoFactorAuthNotification mail subject and body line
- TwoFactorAuthController invalid code errors

Fixes sync mail send hanging on /2fa when subject used _().

https://processmaker.atlassian.net/browse/FOUR-34260

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Agentic Security Review — 1 finding(s).

  • [HIGH] ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php:137 — A password-authenticated session that has not completed 2FA can GET /2fa/auth_app_qr. displayAuthAppQr only checks that a user is present, then generateQr calls getUserTotpSecret, which returns the stored two_factor_secret or mints one and saveQuietly()s it. That secret is placed in the otpauth provisioning URI and returned as the QR image. The same secret is used for email/SMS OTPs (sha512, 8 digits, 300s) and for authenticator codes (default 6-digit TOTP). validateCode treats any 6-character code as authenticator mode, does not consult getValid2FAPreferences, and the controller stores the result in 2fa-validated, which the 2fa middleware accepts as completion. This holds for email-only and SMS-only users and when a secret is already stored. The new redirect in displayTwoFactorAuthForm only sends authenticator-only users with an empty secret to this page; it does not authorize the route. Showing a QR once for that incomplete authenticator enrollment can stay; the route must not mint or re-show the secret for other methods or after a secret already exists, and a 6-digit code must be rejected unless Authenticator App is an enabled method.
    • Impact: An attacker who has the victim's password, or that pre-2FA session, recovers the long-term second-factor secret and can pass the 2FA gate without the victim's email, phone, or authenticator. two_factor_secret is now a confidential persisted credential rather than a value derived from public identity, but this path still discloses it to a session that has only passed primary authentication, and the shared secret unlocks email and SMS as well as authenticator.
    • Remediation: Allow displayAuthAppQr to mint and show a QR only when Authenticator App is an enabled method and enrollment is still incomplete. After two_factor_secret exists, do not return it again to a session that has not just completed enrollment; require a verified second factor before any later display. Keep the email/SMS OTP secret separate from the authenticator secret, and in validateCode accept a 6-digit authenticator code only when Authenticator App is one of that user's enabled methods.

@nolanpro

Copy link
Copy Markdown
Contributor

QA server K8S was successfully deployed https://tenant-1.ci-acbfe4bfe2.engk8s.processmaker.net

Refactor otp and auth_app_qr to extend auth.layouts.auth instead of legacy
standalone HTML, background assets, and inline CSS. Use existing skip-language-
selector and skip-auth-language-scripts sections so 2FA matches password-reset
branding without changing the auth layout.

https://processmaker.atlassian.net/browse/FOUR-34260
Use fresh() instead of User::refresh() on /2fa display so two_factor_secret
is read from the database without invalidating permissions cache.

https://processmaker.atlassian.net/browse/FOUR-34260

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Agentic Security Review — 1 finding(s).

  • [HIGH] ProcessMaker/Http/Controllers/Auth/TwoFactorAuthController.php:137 — A password session that has not set 2fa-validated can GET /2fa/auth_app_qr and receive the durable TOTP seed in the provisioning QR. displayAuthAppQr only checks that a user is present, then generateQr embeds users.two_factor_secret in an otpauth URI. That same seed is what validateCode accepts: code length alone selects the 6-digit authenticator profile or the 8-digit sha512/300s email/SMS profile. After the seed exists, every later password login can read it again, and an email/SMS-only user can open the route directly even though authenticator is not their method.
    • Impact: This is the second-factor possession boundary. Password login already creates a session, and the 2fa middleware only wraps later application routes, so the pre-2FA session is the actor 2FA is meant to stop. The new stored secret is no longer recomputable from uuid and username, but this route still returns it, so a phished or reused password is enough to mint a valid code and set 2fa-validated. That includes users whose only methods are email or SMS, because their emailed or texted code is derived from the seed on the QR. The one-time authenticator enrollment redirect for an empty secret is the intended setup step; repeating the seed, or showing it when authenticator is not enabled, removes the second factor.
    • Remediation: Serve the provisioning QR only for initial authenticator enrollment: authenticator must be an enabled method for that user, and two_factor_secret must still be empty. Call generateQr only in that case, then require a confirming code from the app. After the seed is stored, deny /2fa/auth_app_qr to any session that has not already passed 2FA, including a direct request when the challenge-page link is hidden. Do not create or return the email/SMS seed from this route. Keep validateCode from accepting a profile the user's enabled methods do not allow, so a seed disclosed during authenticator setup cannot also satisfy an email or SMS challenge.

@nolanpro

Copy link
Copy Markdown
Contributor

QA server K8S was successfully deployed https://tenant-1.ci-acbfe4bfe2.engk8s.processmaker.net

…ment

Store email/SMS TOTP in two_factor_delivery_secret and authenticator TOTP in
two_factor_secret. Gate /2fa/auth_app_qr on enabled Authenticator App and empty
enrollment secret; reject six-digit codes unless the method is allowed.

Extend the users migration, tighten OTP link visibility, and add unit/feature
coverage for predictable-secret bypass and QR route access.

https://processmaker.atlassian.net/browse/FOUR-34260

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@nolanpro

Copy link
Copy Markdown
Contributor

QA server K8S was successfully deployed https://tenant-1.ci-acbfe4bfe2.engk8s.processmaker.net

Combine authenticator-method and existing-secret checks into one redirect
to /2fa so displayAuthAppQr stays within the return-statement limit.

https://processmaker.atlassian.net/browse/FOUR-34260
Extract authenticator QR redirect and send-code provisioning into private
helpers so Sonar S3776 stays within the limit.

https://processmaker.atlassian.net/browse/FOUR-34260
Accumulate validation in a $valid flag and return once so validateCode stays
within the return-statement limit without changing 2FA verification behavior.

https://processmaker.atlassian.net/browse/FOUR-34260
…id code

Defer persisting two_factor_secret until a six-digit code verifies. Store the
QR provisioning secret in session so enrollment can be retried without locking
users out of the authenticator link or QR page.

https://processmaker.atlassian.net/browse/FOUR-34260

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@nolanpro

Copy link
Copy Markdown
Contributor

QA server K8S was successfully deployed https://tenant-1.ci-acbfe4bfe2.engk8s.processmaker.net

Do not redirect authenticator-only users back to the QR page when
PENDING_AUTHENTICATOR_SECRET is in session, so they can enter a code after
scanning. Add a feature test that GET /2fa returns the OTP view after QR enrollment.

https://processmaker.atlassian.net/browse/FOUR-34260
@nolanpro

Copy link
Copy Markdown
Contributor

QA server K8S was successfully deployed https://tenant-1.ci-acbfe4bfe2.engk8s.processmaker.net

@julceslauhub
julceslauhub self-requested a review November 10, 2026 20:46

@julceslauhub julceslauhub left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved

@nolanpro

Copy link
Copy Markdown
Contributor

QA server K8S was successfully deployed https://tenant-1.ci-acbfe4bfe2.engk8s.processmaker.net

…roll

Set DELIVERY_STEP_UP after a valid email/SMS code and gate new authenticator
binding on mayEnrollNewAuthenticator. Redirect to the QR screen after
delivery step-up so enrollment is reachable in the login flow (Cursor Bugbot).

https://processmaker.atlassian.net/browse/FOUR-34260
@cursor
cursor Bot requested review from agustinbusso and caleeli November 19, 2026 02:25
Snapshot challenge methods at login; block self-service API updates to
preferences_2fa until TFA is validated. Gate authenticator enrollment on
delivery step-up (session snapshot), redirect to QR after a valid delivery
code, and clear 2FA session keys on logout. Address Cursor Bugbot findings.

https://processmaker.atlassian.net/browse/FOUR-34260

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Only block preferences_2fa when a login challenge snapshot exists and
TFA is not validated; skip SSO and Bearer-only API profile updates.

https://processmaker.atlassian.net/browse/FOUR-34260
Ignore TFA_VALIDATED from another user's cookie when updating
preferences_2fa via API (Cursor Bugbot).

https://processmaker.atlassian.net/browse/FOUR-34260
Gate self-service preferences_2fa updates on a completed web 2FA challenge
bound to the authenticated user. Return 422 while the login challenge is
pending, and skip the gate for SSO sessions. Refactor update() to a single
response path so validation errors stop before any save or event dispatch.

https://processmaker.atlassian.net/browse/FOUR-34260
…ble ones

Stop deriving TOTP secrets from the user UUID and username. Authenticator
secrets are now random and stored in two_factor_secret. A new authenticator
can only be enrolled after a delivery-code step-up when the policy requires
one, and the enrollment snapshot is taken at login.

Remove the predictable secret generator and the unused getUserTotpSecret
helper (Sonar S1144). Simplify validateCode and createOtpInstance to satisfy
S1142 and S1488.

https://processmaker.atlassian.net/browse/FOUR-34260
…onar S1142

Combine the existing-secret and missing AUTH_APP checks into one guard so
the method stays within the three return-statement limit without changing
enrollment behavior.

https://processmaker.atlassian.net/browse/FOUR-34260
…2FA completes

Reject PUT /api/1.0/users/{user} when the principal updates their own
preferences_2fa while a login challenge snapshot is active, SSO is not in
use, and the web session has not completed 2FA for the same user id. Prevents
narrowing 2FA methods to skip delivery step-up during an in-progress challenge.

https://processmaker.atlassian.net/browse/FOUR-34260
Use a single final redirect with a $route variable instead of a separate
return for authenticator QR enrollment, preserving mixed-method flow behavior.

https://processmaker.atlassian.net/browse/FOUR-34260
…r S1142 and S3776

Address Sonar findings on UserController::update(): rule S1142 (too many return
statements) and rule S3776 (cognitive complexity above the allowed threshold).
Move post-fill validation and persistence into private helpers without changing
behavior. The 2FA preferences_2fa gate, cell validation, email change checks, and
save/avatar flow remain the same as before this refactor.

https://processmaker.atlassian.net/browse/FOUR-34260
…validated web session

Require web guard and TFA_VALIDATED for self-service preferences_2fa when global 2FA
applies. Extract UserController::update validation helpers for Sonar S1142 and S3776.
Add feature test with a valid update payload asserting the 2FA guard message.

https://processmaker.atlassian.net/browse/FOUR-34260
Reject self-service PUT updates to preferences_2fa, email, and cell when global
2FA applies and the principal has not completed the web session challenge
(TFA_VALIDATED), closing Bearer and password-only API bypasses of delivery step-up.
Snapshot challenge delivery email and cell at login and send OTP to those targets.
Add feature tests for stateless API preferences and email changes.

https://processmaker.atlassian.net/browse/FOUR-34260

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@decisions-sonarqube

Copy link
Copy Markdown

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Use session()->exists() so snapshotted null cell is applied instead of the
live user attribute from replicate(), matching frozen email behavior.

https://processmaker.atlassian.net/browse/FOUR-34260
Require the web session user to match the API bearer before honoring
sso_driver; block foreign SSO cookies from bypassing preferences_2fa and
cell changes. After delivery step-up, skip repeated delivery OTPs on /2fa
and send-again, keep users on the OTP form when re-submitting an 8-digit
code, and redirect to QR only for the first authenticator enrollment step.

Feature tests cover SSO cross-session bypass, enrollment resend, and second
delivery code behavior.

https://processmaker.atlassian.net/browse/FOUR-34260
… checks

Defer TFA_VALIDATED until authenticator enrollment when the login snapshot
requires it, bind pending QR secrets to the user id, use session exists for
the methods snapshot, require a real SSO binding before skipping the API
self-update gate, and block preferences_2fa API changes only when values
change. Add feature and unit tests for gate behavior, spoofed sso_driver, and
admin updates.

https://processmaker.atlassian.net/browse/FOUR-34260

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

…hout losing functionality

Unify challenge method resolution, eliminate enrollment ambiguity, and
strengthen session-user binding for snapshots.

Changes:
1. Add challengeMethods() - single source for snapshot vs live preferences
2. Add enrollment helpers - needsAuthenticatorEnrollment,
   isInAuthenticatorEnrollmentPhase, shouldShowQrForFirstTime
3. Remove $hadDeliveryStepUp variable - use isInAuthenticatorEnrollmentPhase()
4. Add reloadUser() helper for DRY in controller
5. Move API gate selfServiceUpdateRequiresTwoFactorCompletion() to service
6. Bind challenge methods snapshot to user ID for cross-session protection

All 32 tests pass (102 assertions). No functional changes.

https://processmaker.atlassian.net/browse/FOUR-34260

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit f073fb0. Configure here.


if ($this->userHasSsoBinding($apiUser)) {
return false;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SSO binding skips 2FA lock

High Severity

selfServiceUpdateRequiresTwoFactorCompletion now skips the self-service 2FA gate for any user with an LDAP or SsoUser binding, even when sso_driver is unset and web 2FA is still required. A password-login SSO-bound user on the 2FA page can PUT cell or preferences_2fa and drop delivery step-up.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit f073fb0. Configure here.

// Check if there's a pending authenticator secret in session
// User ID validation is performed when generating the secret
return session()->has(self::PENDING_AUTHENTICATOR_SECRET);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pending TOTP secret ignores user

High Severity

sessionHasPendingAuthenticatorForUser now returns true whenever PENDING_AUTHENTICATOR_SECRET exists and never compares PENDING_AUTHENTICATOR_USER_ID. resolveAuthenticatorSecret and generateQr will reuse another user's pending secret, and enrollment/QR routing follows that leftover secret. The cross-user unit test was removed.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit f073fb0. Configure here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants